const WebSocket = require('ws').WebSocket; // 获取WebSocket构造函数
const EventEmitter = require('events');

class WebsocketUtil extends EventEmitter {
    constructor(url) {
        super();
        this.url = url;
        this.ws = null;
        this.connecting = false;
    }

    connect() {
        return new Promise((resolve, reject) => {
            if (this.ws) {
                return resolve(); // 已经连接
            }

            this.connecting = true;
            console.log('websocketUtil', this.url);
            this.ws = new WebSocket(this.url);

            this.ws.on('open', () => {
                this.connecting = false;
                console.log('Connected to WebSocket server');
                resolve();
            });

            this.ws.on('message', (message) => {
                let data;
                try {
                    data = JSON.parse(message);
                    console.log(data)
                } catch (e) {
                    console.error('Failed to parse message:', e);
                    return; // 解析失败则忽略此消息
                }

                if (data && typeof data === 'object') {
                    let event = data.event || 'defaultEvent';
                    let dataContent = data.data || '';
                    let fromCode = data.fromCode || '';

                    this.emit(event, data);
                } else {
                    console.warn('Received malformed data:', data);
                }
            });

            this.ws.on('error', (error) => {
                this.connecting = false;
                console.error('WebSocket error:', error);
                reject(error);
            });

            this.ws.on('close', () => {
                this.connecting = false;
                console.log('WebSocket connection closed');
                this.ws = null;
            });
        });
    }

    send(event, data) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            console.log('Send to WebSocket event:', event);
            console.log('Send to WebSocket data:', data);
            this.ws.send(JSON.stringify({ event, data }));
        } else {
            console.error('WebSocket is not connected.');
        }
    }

    sendData(data) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(data);
        } else {
            console.error('WebSocket is not connected.');
        }
    }

    invoke(event, data, answerEvent) {
        return new Promise((resolve, reject) => {
            this.send(event, data);
            this.once(answerEvent, resolve);
            setTimeout(() => {
                reject(new Error('timeout'));
            }, 5000);
        });
    }

    disconnect() {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.close();
        }
        this.removeAllListeners();
    }
}

module.exports = WebsocketUtil;